package com.xjc.business.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.xjc.business.entity.domain.xlsx.StuImportEntity;
import com.xjc.business.entity.vo.coladmin.ClassVo;
import com.xjc.business.entity.vo.coladmin.MajorVo;
import com.xjc.business.entity.vo.coladmin.MajorWithClass;
import com.xjc.business.entity.vo.xlsx.ExportCheckBedTableVo;
import com.xjc.business.service.CheckBedBackService;
import com.xjc.business.service.ClazzsService;
import com.xjc.business.service.MajorsService;
import com.xjc.business.service.StudentsService;
import com.xjc.system.constants.MyConstants;
import com.xjc.system.exception.MyException;
import com.xjc.system.listener.UserDataListener;
import com.xjc.system.result.Result;
import com.xjc.system.result.ResultCode;
import com.xjc.system.utils.TokenUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 徐锦程
 * 时间:2025-01-30 11:37
 */
@RestController
@RequestMapping("/xlsx")
@CrossOrigin
public class XlsxController {

    @Autowired
    MajorsService majorsService;

    @Autowired
    StudentsService studentsService;

    @Autowired
    CheckBedBackService checkBedBackService;

    /**
     * 下载批量导入学生模版
     * @param collegeId 学院id
     * @return 文件流
     */
    @GetMapping("/download/template/importstu/{collegeId}/{token}")
    public void downloadFile(@PathVariable Integer collegeId, @PathVariable(value = "token",required = false) String token, HttpServletResponse response) {
        if (token==null|| !TokenUtils.isTokenValid(token)){
            throw new MyException(ResultCode.UNAUTHORIZED.getCode(),ResultCode.UNAUTHORIZED.getMessage());
        }
        if (collegeId==null){
            throw new MyException(ResultCode.SUCCESS.getCode(), MyConstants.PARAM_MISSING);
        }
        Workbook workbook = null;
        try {
            // 专业列表
            List<MajorWithClass> majorData = majorsService.getMajorWithClassList(collegeId).getData();
            List<String> majorList = majorData.stream().map(MajorWithClass::getMajorName).collect(Collectors.toList());
            String[] majorNameList = new String[majorList.size()];
            StringBuilder classNumListBuilder = new StringBuilder();
            for (int i = 0; i < majorList.size(); i++) {
                majorNameList[i] = majorList.get(i);
                classNumListBuilder.append("【"+majorList.get(i)+"】专业有 "+majorData.get(i).getClassVoList().size()+" 个班级；");
            }

            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("学生导入模版.xlsx", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            // 使用 Apache POI 加载模板文件
            ClassPathResource resource = new ClassPathResource("templates/import_stu_template.xlsx");
            File file = resource.getFile();

            try (FileInputStream fileInputStream = new FileInputStream(file)) {
                workbook = new XSSFWorkbook(fileInputStream);
            }

            // 获取第一个 Sheet
            Sheet sheet = workbook.getSheetAt(0);

            sheet.getRow(1).getCell(0).setCellValue(classNumListBuilder.toString());
            setDropdownList(sheet, 3, 999, 1, 1, majorNameList);

            // 将修改后的内容写入响应流
            try (OutputStream outputStream = response.getOutputStream()) {
                workbook.write(outputStream);
            }

        }
        catch (Exception e){
            e.printStackTrace();
        }finally {
            if(workbook!=null){
                // 关闭 Workbook
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 下载查寝结果表格
     * @param checkBedBackId 查寝反馈id
     * @return 文件流
     */
    @GetMapping("/download/template/chechbedtable/{checkBedBackId}/{token}")
    public void exportCheckBedTable(@PathVariable(value = "checkBedBackId",required = false) Integer checkBedBackId, @PathVariable(value = "token",required = false) String token, HttpServletResponse response){
        if (token==null|| !TokenUtils.isTokenValid(token)){
            throw new MyException(ResultCode.UNAUTHORIZED.getCode(),ResultCode.UNAUTHORIZED.getMessage());
        }
        if (checkBedBackId==null){
            throw new MyException(ResultCode.SUCCESS.getCode(), MyConstants.PARAM_MISSING);
        }
        Workbook workbook = null;

        try{
            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("查寝结果.xlsx", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            // 使用 Apache POI 加载模板文件
            ClassPathResource resource = new ClassPathResource("templates/check_bed_report_template.xlsx");
            File file = resource.getFile();


            try (FileInputStream fileInputStream = new FileInputStream(file)) {
                workbook = new XSSFWorkbook(fileInputStream);
            }

            // 获取第一个 Sheet
            Sheet sheet = workbook.getSheetAt(0);

            ExportCheckBedTableVo exportCheckBedTableVos = checkBedBackService.getExportCheckBedTableVoList(checkBedBackId);

            sheet.getRow(0).getCell(0).setCellValue(exportCheckBedTableVos.collegeName+"-"+exportCheckBedTableVos.getTypeOne()+"-"+exportCheckBedTableVos.getTypeTwo()+" 学生名单");
            sheet.getRow(1).getCell(1).setCellValue(exportCheckBedTableVos.getTime());

            CellStyle style = workbook.createCellStyle(); // 创建单元格样式
            style.setAlignment(HorizontalAlignment.CENTER); // 设置水平居中对齐

            // 设置边框
            style.setBorderTop(BorderStyle.THIN);
            style.setBorderBottom(BorderStyle.THIN);
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);

            List<ExportCheckBedTableVo.StuInfoVo> stuInfoVoList = exportCheckBedTableVos.stuInfoVoList;
            for (int i = 0; i < stuInfoVoList.size(); i++) {
                ExportCheckBedTableVo.StuInfoVo stuInfoVo = stuInfoVoList.get(i);

                Row row = sheet.createRow(i + 3);

                Cell cell1 = row.createCell(0);
                cell1.setCellStyle(style);
                cell1.setCellValue(i+1);

                Cell cell2 = row.createCell(1);
                cell2.setCellStyle(style);
                cell2.setCellValue(stuInfoVo.getSno());

                Cell cell3 = row.createCell(2);
                cell3.setCellStyle(style);
                cell3.setCellValue(stuInfoVo.getStuName());

                Cell cell4 = row.createCell(3);
                cell4.setCellStyle(style);
                cell4.setCellValue(stuInfoVo.getSex());

                Cell cell5 = row.createCell(4);
                cell5.setCellStyle(style);
                cell5.setCellValue(stuInfoVo.getMajorClass());

                Cell cell6 = row.createCell(5);
                cell6.setCellStyle(style);
                cell6.setCellValue(stuInfoVo.getBedNum());
            }
            // 将修改后的内容写入响应流
            try (OutputStream outputStream = response.getOutputStream()) {
                workbook.write(outputStream);
            }


        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(workbook!=null){
                // 关闭 Workbook
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 上传excel
     * @param file 文件
     */
    @PostMapping("/upload/{token}/{collegeId}")
    public Result<String> uploadExcel(@RequestParam("file") MultipartFile file,@PathVariable(value = "token",required = false) String token,@PathVariable(value = "collegeId",required = false) Integer collegeId) throws IOException {
        if (token==null|| !TokenUtils.isTokenValid(token)){
            throw new MyException(ResultCode.UNAUTHORIZED.getCode(),ResultCode.UNAUTHORIZED.getMessage());
        }
        if (file.isEmpty()) {
            throw new MyException(ResultCode.SUCCESS.getCode(), MyConstants.PARAM_MISSING);
        }

        UserDataListener listener = new UserDataListener();
        EasyExcel.read(file.getInputStream(), StuImportEntity.class, listener)
                .sheet()
                .headRowNumber(3)
                .doRead();

        // 读取的Xlsx文件内容
        List<StuImportEntity> dataList = listener.getDataList();

        // 保存到数据库
        try {
            studentsService.batchAddStudent(dataList,collegeId);
        }catch (Exception e){

        }

        return Result.okWithData("批量导入完成");
    }

    /**
     * 设置下拉列表
     */
    private void setDropdownList(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol, String[] options) {
        DataValidationHelper helper = sheet.getDataValidationHelper();
        DataValidationConstraint constraint = helper.createExplicitListConstraint(options);
        CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
        DataValidation validation = helper.createValidation(constraint, addressList);
        sheet.addValidationData(validation);
    }
}
